<!--
 * @author  dumeng
-->
<template>
  <div class="check-all-check-box">
    <el-checkbox
      v-model="checkAll"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange"
    >全选</el-checkbox>
    <el-checkbox-group
      v-model="checkedList"
      class="can-check-all"
      style="margin-top:15px;"
      @change="handleCheckedChange"
    >
      <el-checkbox
        v-for="(item,index) in options"
        :key="index"
        :label="item[bindVal]"
      >{{ item[name] }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script>

export default {
  name: 'Index',
  model: {
    prop: 'checkList',
    event: 'change'
  },
  props: {
    // 选择的值
    checkList: {
      type: Array,
      default: () => []
    },
    // 多选选项
    options: {
      type: Array,
      default: () => []
    },
    // 绑定的值
    bindVal: {
      type: String,
      default: ''
    },
    // name
    name: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isIndeterminate: false,
      checkAll: false,
      checkedList: this.checkList
    }
  },
  watch: {
    checkList(arr) {
      if (arr.length <= 0) {
        this.checkAll = false
        this.isIndeterminate = false
        this.checkedList = []
      }
    }
  },
  methods: {
    handleCheckAllChange(val) {
      this.$set(this, 'checkedList', val ? this.options.map(item => item.id) : [])
      this.$emit('change', val ? this.options.map(item => item.id) : [])
      this.isIndeterminate = false
    },
    handleCheckedChange(val) {
      this.$emit('change', this.checkedList)
      const checkedCount = val.length
      this.checkAll = checkedCount === this.options.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.options.length
    }
  }
}
</script>

<style lang="scss">
.check-all-check-box {
  .el-checkbox-group.can-check-all {
    margin-left: 0;
  }
  .el-checkbox {
    margin-right: 10px;
  }
}
</style>
